import * as BASE from '@/stores/definitions-base';
import { Input, Switch, DatePicker, Radio, NumberPicker } from '@alifd/next';
import { t } from '@lingui/macro';
import React from 'react';
import { ellipsisRender } from '@/components/TauTable';
import TauSimpleSelect from '@/components/TauSimpleSelect';
import moment from 'moment';
import TauRichEditor from '@/components/TauRichEdit';
import { DictItemSelect } from '@/components/biz';

const RadioGroup = Radio.Group;

const {
  DATETIME_TEXT,
  DATE_TEXT,
  TIME_TEXT,
  EMPTY_TEXT,
  ENUMS: ENUMSBase,
  FieldsGrid: FieldGridBase,
  TitleGrid,
  column: columnBase,
  toSelectDataSource,
} = BASE;
export { DATETIME_TEXT, DATE_TEXT, EMPTY_TEXT, TIME_TEXT, TitleGrid, toSelectDataSource };

/**
 * @param {*} path        属性path
 * @param {*} props       column属性
 * @returns column定义
 */
export function column(...args) {
  return columnBase(model, ...args);
}

/**
 * 显示一组表单字段
 * ```js
 * {
 *   fields: string[],    // 字段名称，可以使用.来指定嵌套对象属性，例如order.busOrder.shift
 *   columns: number,     // 列数，默认为4,最大为12,最小为1
 *   model: object,       // 字段定义数据模型的根对象，默认不指定，仅在使用子对象作为根模型时设置
 *   overrideModel: object, // 重载字段定义数据模型
 *   mode: string,        // 表单模式，默认为edit，可选view
 *   itemLayout: object,  // FormItem布局配置，默认为{}
 * }
 * ```
 *
 * @param {object} param0
 * @returns
 */
export function FieldsGrid(props) {
  return <FieldGridBase model={model} {...props} />;
}

//----------------------------------------------------------------------
export const ENUMS = {
  ...ENUMSBase,
  state: { // 启用状态
    true: t`启用`,
    false: t`禁用`,
  },
  type: {
    1: t`立减活动`,
    2: t`新客礼包`,
    3: t`客服发放优惠券`,
    4: t`员工发券`,
    5: t`普通发券`,
  },
  // 通知相关
  notifyType: {
    normal: t`普通通知`,
    headline: t`置顶通知`,
  },
  // <br/> app - 内部通知<br/> email - 邮件通知<br/> sms - 短信通知<br/> wx - 微信通知<br/> 可同时指定多个发送类别
  notifySendTypes: {
    app: t`内部通知`,
    email: t`邮件通知`,
    sms: t`短信通知`,
    wx: t`微信通知`,
  },
  positioningRole: {
    0: t`未注册`,
    1: t`已注册`,
  },
  monitorType: {
    0: t`比例值`,
    1: t`具体类型`,
  },
  path: {
    1: 'pages/home/index',
    2: 'pages/sub/activity',
    3: 'pages/sub/activity',
    4: 'pages/sub/activity',
    5: 'pages/sub/activity',
    6: 'pages/sub/activity',
  },
  sceneType: {
    partner: t`合伙人`,
    merchant: t`渠道商户`,
    official: t`公众号`,
    company: t`公司`,
    driver: t`司机`,
    activity: t`活动`,
  },
};

/**
 * 模型定义：
 * 1. 普通文本仅需要定义label
 * 2. 需要通过枚举转换的值，定义text; 当使用renderer返回组件时，text属性无效，需要通过组件的renderPreview来指定预览时的绘制方式
 * 3. 通用的ui属性需要定制时，定义ui; 特定模式(view, edit, add)下的ui，添加后缀定义为ui_<mode>，例如：ui_view, ui_edit, ui_add, ui_table
 * 4. ui可配置属性包括:
 *    renderer: 内容渲染函数, Form表单中的原型为：(value: any, formData: any, fieldDefinition: any) => ReactNode; Table Column中的原型为: (value: any, columnIndex: number, rowData: any) => ReactNode;
 *    itemProps: 表单Form.Item的属性，可以是对象，或函数({ isPreview: boolean, mode: string, value: any, formData: any, ...otherDefinitions}) => void;
 *    span: Grid Cell占用的列数, 默认为1
 *
 * 【注】获取接口的model定义后，vscode中通过正则替换：^(\s+)"label": "([^']+)"  ===> $1label: t`$2`
 */
export const model = {
  id: {
    label: t`标识`,
  },
  quota: {
    label: t`名额`,
  },
  type: {
    label: t`活动类型`,
    ui: {
      renderer: (v) => <TauSimpleSelect data={toSelectDataSource(ENUMS.type)} value={v} />,
      itemProps: { required: true },
    },
    ui_table: {
      renderer: (v) => <span>{ENUMS.type[v]}</span>,
    },
  },
  name: {
    label: t`名称`,
    ui: {
      renderer: (v) => <Input value={v} placeholder="请输入名称" />,
      itemProps: { required: true },
    },
  },
  enabled: {
    label: t`状态`,
    ui_table: {
      renderer: (v, _, row) => <Switch checkedChildren="启用" unCheckedChildren="禁用" checked={Number(v) === 1} size="small" autoWidth onClick={() => rootStore.activityStore.updateState(row)} />,
    },
    ui: {
      renderer: (v, _, __) => <Switch checkedChildren="启用" unCheckedChildren="禁用" checked={Number(v) === 1} size="small" autoWidth />,
    },
  },
  link: {
    label: t`活动推文链接`,
    text: (v) => ellipsisRender(v),
    ui: {
      renderer: (v) => <Input value={v} placeholder="请输入活动推文链接" />,
      span: 2,
    },
  },
  whiteList: {
    label: t`白名单`,
    text: (v) => ellipsisRender(v?.join(',')),
  },
  crBy: {
    label: t`创建者`,
  },
  upBy: {
    label: t`最后修改者`,
  },
  mobile: {
    label: t`手机号`,
  },
  orderCount: {
    label: t`相关订单`,
  },
  description: {
    label: t`说明`,
    ui: {
      renderer: (v) => <Input.TextArea aria-label="auto height" autoHeight={{ minRows: 6 }} value={v} />,
      itemProps: { required: true },
      span: 3,
    },
  },
  crDate: {
    label: t`创建时间`,
    text: DATETIME_TEXT,
  },
  upDate: {
    label: t`更新时间`,
    text: DATETIME_TEXT,
  },
  tenantId: {
    label: t`租户ID`,
  },
  deadline: {
    label: t`有效期限`,
    ui_table: {
      renderer: (v, _, r) => {
        let timeType;
        let high;
        let low;
        let expirationDate = '无';
        if (typeof r?.rules?.有效期 === 'string') {
          timeType = true;
          const day = r?.rules?.有效期;
          const duration = moment.duration(day);
          expirationDate = duration.humanize();
        } else {
          timeType = false;
          high = r?.rules?.有效期?.highEndPoint?.c;
          low = r?.rules?.有效期?.lowEndPoint?.c;
        }
        return (
          <>
            {
              timeType ?
                <>
                  <span>{expirationDate}</span>
                </>
                :
                <>
                  <span>{low ? moment.unix(low).format('YYYY-MM-DD') : '无'}</span>
                  <br />
                  <span>{high ? moment.unix(high).format('YYYY-MM-DD') : ''}</span>
                </>
            }
          </>
        );
      },
    },
  },
  announcement: {
    label: t`活动公告`,
    title: {
      label: t`标题`,
      ui: {
        itemProps: { required: true },
      },
    },
    text: {
      label: t`内容`,
      ui: {
        renderer: (v) => <TauRichEditor editorProps={{ initialValue: v }} />,
      },
    },
    pictures: {
      label: t`图片`,
    },
    link: {
      label: t`链接`,
    },
    beginTime: {
      label: t`开始时间`,
    },
    endTime: {
      label: t`结束时间`,
    },
    timeRange: {
      label: t`时间范围`,
      ui: {
        renderer: (v) => <DatePicker.RangePicker value={v} format="YYYY-MM-DD" />,
      },
    },
    enable: {
      label: t`启用状态`,
      ui: {
        renderer: (v) => <Switch checked={v} checkedChildren="启用" unCheckedChildren="禁用" autoWidth size="small" />,
      },
    },
    place: {
      label: t`弹窗位置`,
      ui: {
        renderer: (v) => <DictItemSelect dictId="travelPagePath" value={v} />,
        itemProps: { required: true },
      },
    },
    signState: {
      label: t`定位角色`,
      ui: {
        renderer: (v) => <TauSimpleSelect data={toSelectDataSource(ENUMS.positioningRole)} value={v} />,
        itemProps: { required: true },
      },
    },
  },
  notify: {
    label: t`活动通知`,
    scope: {
      label: t`相关应用Scope`,
    },
    sender: {
      label: t`发送者帐号`,
    },
    recipient: {
      label: t`接收者帐号`,
      text: (v) => ellipsisRender(v),
    },
    subject: {
      label: t`通知主题`,
      text: (v) => ellipsisRender(v),
      ui: {
        itemProps: { required: true },
      },
    },
    content: {
      label: t`通知内容`,
      text: (v) => ellipsisRender(v),
      ui: {
        renderer: (v) => <Input.TextArea value={v} />,
        itemProps: { required: true },
      },
    },
    businessKey: {
      label: t`关联的业务标识`,
    },
    notifyType: {
      label: t`类型`,
      text: (v) => ENUMS.notifyType[v],
      ui: {
        renderer: (v) => <TauSimpleSelect value={v} dataSource={toSelectDataSource(ENUMS.notifyType)} />,
        itemProps: { required: true },
      },
    },
    notifySendTypes: {
      label: t`通知发送类别`,
      text: (v) =>
        v?.map((p) => (
          <>
            <span>{ENUMS.notifySendTypes[p]}</span>
            {v?.length > 1 && <br />}
          </>
        )),
      ui: {
        renderer: (v) => <TauSimpleSelect value={v} mode="multiple" dataSource={toSelectDataSource(ENUMS.notifySendTypes)} />,
        itemProps: { required: true },
      },
    },
    crDate: {
      label: t`创建时间`,
      text: DATETIME_TEXT,
    },
    tenantId: {
      label: t`租户ID`,
    },

    // 前端新增字段
    sendType: {
      label: t`通知模式`,
      ui: {
        renderer: (v) => (
          <RadioGroup value={v} aria-labelledby="groupId">
            <Radio id="day" value="day">
              {t`按天通知`}
            </Radio>
            <Radio id="time" value="assignDay">
              {t`固定周期`}
            </Radio>
          </RadioGroup>
        ),
      },
    },
    popupType: {
      label: t`弹窗模式`,
      ui: {
        renderer: (v) => (
          <RadioGroup value={v} aria-labelledby="groupId">
            <Radio id="day" value="1">
              {t`已读不弹`}
            </Radio>
            <Radio id="time" value="0">
              {t`重复弹窗`}
            </Radio>
          </RadioGroup>
        ),
      },
    },
    period: {
      label: t`日期周期`,
      ui: {
        renderer: (v) => <DatePicker.RangePicker value={v} format="YYYY-MM-DD" hasClear outputFormat={DATE_TEXT} />,
      },
    },
    weekdays: {
      label: t`固定周期`,
      ui: {
        renderer: (v) => (<TauSimpleSelect
          value={v}
          mode="multiple"
          dataSource={
            [
              { label: t`周一`, value: 1 },
              { label: t`周二`, value: 2 },
              { label: t`周三`, value: 3 },
              { label: t`周四`, value: 4 },
              { label: t`周五`, value: 5 },
              { label: t`周六`, value: 6 },
              { label: t`周日`, value: 7 },
            ]
          }
        />),
      },
    },
    recipients: {
      label: t`接收者列表`,
      ui: {
        itemProps: { required: true },
      },
    },
    addRecipients: {
      label: t`添加接收者`,
    },
  },
  extra: {
    label: t`自定义数据`,
  },
  // 前端新增模型
  serviceName: {
    label: t`客服名称`,
  },
  serviceMobile: {
    label: t`客服号码`,
  },
  serviceList: {
    label: t`客服列表`,
  },
  customerMobile: {
    label: t`客户号码`,
  },
  customerList: {
    label: t`客户列表`,
  },
  couponBatchId: {
    label: t`卡券批次`,
  },
  activityId: {
    label: t`活动名称`,
  },
  number: {
    label: t`发放数量`,
  },
  couponCount: {
    label: t`卡券数量`,
  },
  batchId: {
    label: t`批次名称`,
  },
  batchList: {
    label: t`批次列表`,
  },
  couponBatchList: {
    label: t`卡券信息`,
  },
  priceCount: {
    label: t`申领 / 发放 / 消费`,
  },
  noticeConfigure: {
    label: t`通知配置`,
    monitorType: {
      label: t`监控类型`,
      ui: {
        renderer: (v) => (
          <RadioGroup value={v} aria-labelledby="groupId">
            <Radio id="1" value={'0'}>
              {t`比例`}
            </Radio>
            <Radio id="2" value={'1'}>
              {t`具体值`}
            </Radio>
          </RadioGroup>
        ),
        itemProps: { required: true },
      },
    },
    value: {
      label: t`监控值`,
      ui: {
        renderer: (v) => <NumberPicker value={v} min={0} max={999} />,
        itemProps: { required: true, format: 'number' },
      },
    },
    sendBatchIds: {
      label: t`发过通知批次的值`,
    },
  },
  activePageSetting: {
    label: t`活动界面配置`,
    buttonText: {
      label: t`按钮文字`,
    },
    link: {
      label: t`跳转链接`,
    },
    attachments: {
      label: t`图片`,
      title: {
        label: t`图片标题`,
      },
      description: {
        label: t`图片说明`,
      },
      binaryId: [
        {
          label: t`图片id`,
        },
      ],
    },
  },
};
